//
// Created by yasin on 2024/9/9.
//

#ifndef WEBRTC_CLIENT__WEB_SOCKET_CLIENT_H_
#define WEBRTC_CLIENT__WEB_SOCKET_CLIENT_H_

#include <websocketpp/config/asio_no_tls_client.hpp>
#include <websocketpp/client.hpp>
#include <thread>

#include "rtc_base/thread.h"

using WSClient = websocketpp::client<websocketpp::config::asio_client>;
using WSMessagePtr = websocketpp::config::asio_client::message_type::ptr;

namespace ohosrtc {

template<typename... Args>
using SuccessCallback = std::function<void(Args ...)>;
using FailCallback = std::function<void(const std::string &)>;

using WebSocketMessageHandler = std::function<void(const std::string &msg)>;

class WebSocketClient : public std::enable_shared_from_this<WebSocketClient> {

 public:
  WebSocketClient(std::shared_ptr<rtc::Thread> worker_thread);
  void Connect(const std::string &ws_url, SuccessCallback<> success_cb, FailCallback fail_cb);
  void SendMessage(const std::string &message, SuccessCallback<> success_cb = nullptr, FailCallback fail_cb = nullptr);
  void SetMessageHandler(WebSocketMessageHandler handler);
  void Disconnect();

  std::unique_ptr<WSClient> ws_client_;
  websocketpp::connection_hdl ws_connection_;
  WebSocketMessageHandler message_handler_;
  std::unique_ptr<std::thread> ws_run_thread_;
  std::shared_ptr<rtc::Thread> worker_thread_;
  std::mutex connection_mutex_;
};

}

#endif //WEBRTC_CLIENT__WEB_SOCKET_CLIENT_H_
